<template>
  <el-container>
    <el-header>
      <div class="header-content">任务点学习</div>
    </el-header>

    <el-main>
      <div v-if="task">
        <div>{{ task.name }}</div>
        <div>{{ task.description }}</div>
        <el-button v-if="!task.completed" @click="updateProgress(true)">标记为已学</el-button>
        <el-button v-else disabled>已学</el-button>
      </div>
      <div v-else>
        <p>任务点信息加载失败。</p>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '@/utiles/axios';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const task = ref(null);
const router = useRouter();
const route = useRoute();

// 获取任务点信息
const getTaskDetails = async () => {
  const taskId = route.params.taskId;  // 从路由中获取任务点ID
  if (!taskId) {
    ElMessage.error('无法获取任务点信息');
    return;
  }

  try {
    const response = await axios.get(`/task/${taskId}`);
    task.value = response.data;
  } catch (error) {
    console.error('获取任务点信息失败', error);
    ElMessage.error('获取任务点信息失败');
  }
};

// 更新任务点学习进度
const updateProgress = async (completed) => {
  const studentId = localStorage.getItem('studentId');  // 从本地存储获取学员ID
  if (!studentId) {
    ElMessage.error('无法获取学员信息');
    return;
  }

  try {
    const response = await axios.put(`/student/${studentId}/progress/${task.value.id}`, null, {
      params: { Completed: completed }
    });
    task.value.completed = completed;  // 更新本地状态
    ElMessage.success('任务点进度更新成功');
  } catch (error) {
    console.error('更新学习进度失败', error);
    ElMessage.error('更新学习进度失败');
  }
};

onMounted(() => {
  getTaskDetails();  // 页面加载时获取任务点信息
});
</script>

<style scoped>
.header-content {
  font-size: 20px;
  font-weight: bold;
  padding: 20px;
}
</style>
